<template>
  <el-card style="margin-bottom:20px;">
    <div slot="header" class="clearfix">
      <span>个人信息</span>
      <el-button type="primary"  style="float: right;margin: 5px" @click="modifyPassword">修改密码</el-button>
    </div>

    <div class="user-profile">
      <div class="box-center">
        <pan-thumb :image="user.avatar" :height="'100px'" :width="'100px'" :hoverable="false">
          <div>Hello</div>
          {{ user.role }}
        </pan-thumb>
      </div>
      <div class="box-center">
        <div class="user-name text-center">{{ user.name }}</div>
        <div class="user-role text-center text-muted">{{ user.role | uppercaseFirst }}</div>
      </div>
      <div style="float: right;margin: 5px">
        <el-upload
          class="upload-demo"
          ref="upload"
          action=""
          accept="image/jpeg,image/jpg,image/png,pdf"
          :limit="1"
          :file-list="fileList"
          :http-request="uploadAvatar">
          <el-button size="small" type="primary">上传头像</el-button>
        </el-upload>
      </div>
      <el-card class="box-card" style="width: 100%; margin-top: 10px">
        <template #header>
          <div class="card-header">
            <el-tag><span style="font-weight: bold;font-size: 15px">个人信息</span></el-tag>
          </div>
        </template>
        <el-form ref="profileForm" :model="profile" label-width="100px" inline label-position="left">
          <el-form-item label="个性签名" required>
            <el-input v-model="profile.remark" ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" required>
            <el-input v-model="profile.email" ></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-check" style="float: right;margin: 5px" circle @click="onSubmitProfile"></el-button>
      </el-card>

      <el-dialog :visible.sync="dialogVisible" title="修改密码">
        <el-form :model="password" label-width="90px" status-icon :rules="rules" ref="password" label-position="left">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input type="password" v-model="password.oldPassword" placeholder="旧密码" auto-complete="off"/>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="password.newPassword" placeholder="新密码" auto-complete="off"/>
          </el-form-item>
          <el-form-item label="确认密码" prop="renewpwd">
            <el-input type="password" v-model="password.renewpwd" placeholder="确认密码" auto-complete="off"></el-input>
          </el-form-item>
          <div style="text-align:right;">
            <el-button type="danger" @click="dialogVisible=false">取消</el-button>
            <el-button type="primary" @click="confirmPassword">确定</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import PanThumb from '@/components/PanThumb'
import { modifyAvatar, modifyMine, modifyPassword } from '@/api/user'
import { upload } from '@/api/file'
import { deletePosition } from '@/api/position'

const defaultProfile = {
  email: '',
  remark: ''
}
export default {
  components: { PanThumb },
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: '',
          email: '',
          introduction: '',
          avatar: '',
          role: ''
        }
      }
    }
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (value.toString().length < 6 || value.toString().length > 20) {
        callback(new Error('密码长度为6 - 20个字符'))
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.password.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      profile: Object.assign({}, defaultProfile),
      fileList: [],
      password: {
        oldPassword: '',
        newPassword: '',
        renewpwd: ''
      },
      dialogVisible: false,
      rules: {
        oldPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        renewpwd: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmitProfile() {
      await modifyMine(this.profile)
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: '保存成功, 请重新登录查看',
        type: 'success'
      })
    },
    async uploadAvatar() {
      let form = new FormData();
      this.$refs.upload.uploadFiles.forEach((file) => {
        form.append("file", file.raw);
      });
      await upload(form).then((res) => {
        modifyAvatar(res.data)
      })
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: "操作成功, 头像上传过段时间会同步，请刷新等待",
        type: 'success'
      })
      this.fileList = []
    },
    modifyPassword() {
      this.dialogVisible = true
      this.password = {}
    },
    async confirmPassword() {
      this.$refs['password'].validate((valid) => {
        if (valid) {
          this.$confirm('确定要修改吗?', 'Warning', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async() => {
              await modifyPassword(this.password)
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              // 注销
              await this.$store.dispatch('user/logout')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            })
            .catch(err => {
              console.error(err)
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  },
  created() {
    this.profile.remark = this.user.introduction
    this.profile.email = this.user.email
  },
}
</script>

<style lang="scss" scoped>
.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}

.user-profile {
  .user-name {
    font-weight: bold;
  }

  .box-center {
    padding-top: 10px;
  }

  .user-role {
    padding-top: 10px;
    font-weight: 400;
    font-size: 14px;
  }

  .box-social {
    padding-top: 30px;

    .el-table {
      border-top: 1px solid #dfe6ec;
    }
  }

  .user-follow {
    padding-top: 20px;
  }
}

.user-bio {
  margin-top: 20px;
  color: #606266;

  span {
    padding-left: 4px;
  }

  .user-bio-section {
    font-size: 14px;
    padding: 15px 0;

    .user-bio-section-header {
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 10px;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}
</style>
